package com.zhang.backend.util;

import com.zhang.backend.entity.User;
import com.zhang.backend.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class SecurityUtils {

    /**
     * 从安全上下文中获取当前登录用户的完整实体。
     * @return 当前用户的 User 实体。
     */
    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("Authentication failed: No user is currently authenticated.");
        }

        Object principal = authentication.getPrincipal();
        String username;

        // 【核心修正】从 principal 中安全地获取用户名
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else if (principal instanceof String) {
            username = (String) principal;
        } else {
            throw new RuntimeException("Authentication failed: Principal is not of expected type.");
        }

        if (username == null) {
            throw new RuntimeException("Authentication failed: Username could not be found in principal.");
        }

        // 【核心修正】使用 SpringContextHolder 从容器中获取 UserService Bean，再通过用户名查询数据库
        UserService userService = SpringContextHolder.getBean(UserService.class);
        User user = userService.findByUsername(username);

        if (user == null) {
            throw new RuntimeException("Authenticated user '" + username + "' not found in database.");
        }

        return user;
    }

    /**
     * 获取当前登录用户的ID。
     * @return 当前用户的ID (Long)。
     */
    public static Long getCurrentUserId() {
        return getCurrentUser().getUserId();
    }
}